import pymysql

class MyORM:
    def __init__(self):
        # 建立与数据库的连接
        conn = pymysql.connect(
            host="192.168.1.129",
            port=3306,
            user="admin1",
            password="123",
            database="mumushouji",
            charset="utf8",
            cursorclass=pymysql.cursors.DictCursor,
            autocommit=True
        )
        # 实例化一个游标对象
        cursor = conn.cursor()
        self.cursor = cursor

    def execute(self,sql):
        self.cursor.execute(sql)
        return self.cursor.fetchall()


class Model:
    # 这个构造方法里边的代码是给数据插入的时候用的
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            self.__setattr__(k, v)

    # 通过链式操作来指定查询的列  就是一顿.然后调用各种方法
    def field(self,select_params):
        self.columns = ','.join(select_params)
        return self

    def query(self,**where_params):
        table = self.__class__.__getattribute__(self,'table_name')
        if hasattr(self, 'columns'):
            sql = "select %s from %s " % (self.columns,table)
        else:
            sql = "select * from %s " % (table)
        if where_params is not None:
            sql = sql + " where "
            for k,v in where_params.items():
                sql += " %s='%s' and" % (k,v)
            sql += ' 1=1 limit 1'
            print(sql)
        # return 0
        return MyORM().execute(sql)


    def insert(self):
        # sql = "insert into user(username,password,nickname,picture,job) values (%s)"
        print(self.__dict__)
        keys = []
        values = []
        table = self.__class__.__getattribute__(self, 'table_name')
        for k,v in self.__dict__.items():
            keys.append(k)
            values.append(v)
        sql = "insert into %s(%s) values('%s')" % (table,','.join(keys), "','".join(values))
        return MyORM().execute(sql)

class User(Model):
    table_name = "user"
    def __init__(self, **kwargs):
        super().__init__(**kwargs)


class Article(Model):
    table_name = "article"

if __name__ == "__main__":
    # user = User(username="dazhoulaoshi1",
    #             password="1231",
    #             nickname="大周老师1",
    #             picture="2.jpg",
    #             job="全栈工程师")
    # user.insert()

    user = User()
    # print(user.query())
    # print(user.field(["user_id","username","nickname"]).query())
    print(user.field(["user_id","username","nickname"]).query(user_id=3,username="3@qq.com"))
    print(user.query(user_id=3,username="3@qq.com"))

    article = Article()
    print(article.query())
    print(article.field(["label_name","title"]).query(id=5))
